
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.rmi.*;
import java.rmi.server.*;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class FileService extends UnicastRemoteObject implements FileServiceInterface {

	private static final String ALGORITHM = "AES";
	
	String mysecretkey = "My super amazing secret FILE key";
	
	public FileService() throws RemoteException{
		
	}
	
	public File getFileHandle(String path) throws RemoteException{
		
		System.out.println("FS: Fle path is: " + path);
		File f = new File(path);
		
		if(f.isFile())
			return f;
		else
			return null;
	}
	
	public boolean updateFile(File f, String serverpath){
		File serverfile = new File(serverpath + "/" + f.getName());
		System.out.println("FS: Updating: " + serverfile.getPath());
		try {
			BufferedReader brd = new BufferedReader(new FileReader(f));
			BufferedWriter fout = new BufferedWriter(new FileWriter(serverfile));
			
			while(brd.ready()){
				fout.write(brd.readLine());
			}
			brd.close();
			fout.close();
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	private String encrypt(String msg, byte[] keyValue) throws Exception{
		Key key = new SecretKeySpec(keyValue, ALGORITHM);
		Cipher c = Cipher.getInstance(ALGORITHM);
		c.init(Cipher.ENCRYPT_MODE, key);
		
		String valueToEnc = msg;
		byte[] encValue = c.doFinal(valueToEnc.getBytes());
		String eValue = new BASE64Encoder().encode(encValue);
		return eValue;
	}
	
	private String decrypt(String msg, byte[] keyValue) throws Exception{
		Key key = new SecretKeySpec(keyValue, ALGORITHM);
		Cipher c = Cipher.getInstance(ALGORITHM);
		c.init(Cipher.DECRYPT_MODE, key);
		
		byte[] decordedValue = new BASE64Decoder().decodeBuffer(msg);
		byte[] decValue = c.doFinal(decordedValue);
		String dValue = new String(decValue);
		return dValue;
	}
}
